package com.alexeyhanin.tapestry.goodies.util.select;

import static com.alexeyhanin.tapestry.goodies.util.StringUtil.notNullString;
import org.apache.tapestry5.ValueEncoder;
import org.apache.tapestry5.ioc.services.PropertyAccess;
import org.apache.tapestry5.ioc.services.PropertyAdapter;

import java.util.List;

/**
 * @author aha
 * @since 2009.5.11
 *        $Id: GenericValueEncoder.java 14 2009-11-27 20:11:53Z gagarin61 $
 */
public class GenericValueEncoder<T> implements ValueEncoder<T> {

    private PropertyAdapter idFieldAdapter;
    private List<T> list;

    public GenericValueEncoder(String idField, PropertyAccess propertyAccess, List<T> list) {
        this.list = list;
        if (idField != null && !idField.equalsIgnoreCase("null")) {
            if (list != null && !list.isEmpty()) {
                final T firstElement = list.iterator().next();
                final Class<?> listType = firstElement.getClass();
                idFieldAdapter = propertyAccess.getAdapter(listType).getPropertyAdapter(idField);
            }
        }
    }

    public String toClient(T item) {
        final Object id;
        if (idFieldAdapter != null) {
            id = idFieldAdapter.get(item);
        } else {
            id = item;
        }
        return notNullString(id);
    }

    public T toValue(String clientValue) {
        if (list == null) {
            return null;
        } else if (idFieldAdapter == null) {
            for (T item : list) {
                if (notNullString(item).equals(clientValue)) {
                    return item;
                }
            }
        } else {
            for (T item : list) {
                if (notNullString(idFieldAdapter.get(item)).equals(clientValue)) {
                    return item;
                }
            }
        }
        return null;
    }

}
